<?php declare(strict_types=1);


namespace PinWuYun\domain\service\youZanServer;

use Exception;
use Youzan\Open\Client;
use YouzanCloudBoot\Facades\LogFacade;

/**
 * Created: by zhiJie
 * Date: 2021/6/23
 */
class ImageServer
{
    /** @var string  文件下载位置 */
    const PIC_SAVE_DIR = YZCLOUD_BOOT_APP_DIR.'/app/public/uploads/';

    /**
     * 有赞文件上传，一次仅仅能上传一张图片
     * @param string $accessToken
     * @param string $image 图片路径
     * @return mixed
     * @throws Exception
     */
    public static function uploadImageOne(string $accessToken, string $image)
    {
        /**  检测图片位置 ，如果是远程图片，先下载到本地，再上传 */
        $grep = '/^(http:\/\/|https:\/\/)/';
        preg_match($grep,$image,$matches);
        $upState = false;
        if($matches) {
            /** 获取图片后缀 */
            $picArr = explode('.', $image);
            $suffix = end($picArr);
            $fp = fopen($image,'r');
            $suffix = $suffix==='tbi'?'jpg':$suffix;
            $fileName = random_int(1000,9999) . time() . '.' .$suffix;
            /** 图片下载 */
            $patch = self::PIC_SAVE_DIR. $fileName;
            $upState = file_put_contents($patch, $fp);
        }

        /** 一次仅支持上传一张图片 */
        $client = new Client($accessToken);
        $method = 'youzan.materials.storage.platform.img.upload';
        $apiVersion = '3.0.0';
        $result = $client->post($method, $apiVersion, [], ['image' => $patch]);
        if($upState && $result['success'] === true) {
            /** 上传完删除 */
            unlink($patch);
        }
        fclose($fp);
        if($result['success'] === false) {
            /** 上传失败，日志 */
            LogFacade::error(date('Y-m-d H:i:s') . '文件上传有赞失败,图片位置：' . self::PIC_SAVE_DIR, [
                'name' => $patch,
                'response' => $result
            ]);
        }
        return $result;
    }
}